<?php
/**
 * Protoweb's base controller with base functionality
 */
include_once 'pwcontroller.php';
include_once 'projects.php';

/**
 * The controller view model
 *
 * Public controller methods are friendly urls thanks to {@link http://codeigniter.com
 * Codeigniter}.
 *
 * @author Gonzalez Federico, Viera Leonel
 * @package Protoweb
 * @subpackage controller
 */
class Views extends PwController 
{
    public function __construct()
    {
        parent::__construct();
    }

    public function create($entityID)
    {
        $data['entity']  = new Entity($entityID);
        $data['project'] = $data['entity']->project;
        $data['user']    = Projects::security($data['project']->id, "member");

        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            $this->create_save($data);
        }

        $this->smartyview->render('view_create.html', $data);        
    }

    public function create_save($data)
    {
        $data['view'] = $this->input->post('name');
        $viewContents = file_get_contents($this->config->item('view_generic_tpl'));
        $viewFileName = $data['entity']->singular . '_' . $data['view'];

        file_put_contents($data['project']->viewsTemplatesPath() . $viewFileName . '.tpl', $viewContents);

        redirect(base_url() . 'views/edit/' . $data['entity']->id . '/' . $viewFileName . '/'); 
    }

    public function get($entityID, $viewName, $toParse=null)
    {   
        $entity = new Entity($entityID);

        // Library to manipulate DOM objects similar to jquery
        $this->load->library('Simple_html_dom.php');

        //file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
        $html = file_get_html($entity->project->viewsTemplatesPath() . $viewName . '.tpl', NULL, NULL, NULL, NULL, FALSE, NULL, NULL, FALSE, NULL);


        $script = '';

        // if components the prepare for the design view
        if ($toParse == 'components') {

            // Count components
            $componentsCount = 0;
            foreach ($html->find('pw:component') as $component) {
                $componentsCount++;
            }

            // parse each component
            for ($i=0; $i < $componentsCount; $i++) { 

                // get view component
                $element = $html->find("pw:component",$i);

                // get component object
                $component = Component::getComponent($element->attr['name'], $entity->project);
                $data      = null;

                // prepare data array with component's attrbibutes
                foreach ($component->attributes as $attribute) {
                    if (array_key_exists("data-{$attribute['id']}", $element->attr)) {
                        $data[$attribute['id']] = $element->attr["data-{$attribute['id']}"];
                    }
                }
                
                // get component container (if present)
                $data['pwContainerContent'] = $element->find('pw:container',0);
                $data['pwContainerContent'] = (isset($data['pwContainerContent']) ? $data['pwContainerContent']->innertext : '');

                // get component design view
                $element->outertext = $component->getDesignView($data); 

                // Backup html into string
                $str_html_bkp = $html->root->innertext;

                // Free memory
                $html->clear();
                unset($html);

                // create new dom object from backup
                $html = str_get_html($str_html_bkp, false, false, DEFAULT_TARGET_CHARSET, false, DEFAULT_BR_TEXT);
            }

            // necesary libs and style
            $base_url = base_url();
            $script = "
                <base href='{$entity->project->base_url()}'>
                <link rel='stylesheet' href='{$base_url}assets/css/view_edit.css'>
                <script src='{$base_url}assets/js/libs/jquery-1.7.2.min.js'></script>
                <script src='{$base_url}assets/js/libs/ui/jquery-ui-1.8.21.custom.min.js'></script>
                <script src='{$base_url}assets/js/libs/modernizr-2.5.3-respond-1.1.0.min.js'></script>
                <script>
                    jQuery(document).ready(function(){
                        jQuery('.pw-container').sortable({
                            connectWith:'.pw-container',
                            cursor:'move',
                            opacity:'0.5',
                            forcePlaceholderSize:true,
                            handle: '.pw-component-move',
                            iframeFix: true
                        })
                    });
                </script>
            ";
        }  // if ($toParse == 'components')

        // DOM to string
        $html = $html->save();

        if ($toParse == 'components') {
            $html = "<!DOCTYPE html><html><head>{$script}</head><body>{$html}</body></html>";
        }

        die($html);
    }

    public function save($entityID, $viewName)
    {
        $entity  = new Entity($entityID);
        $content = htmlspecialchars_decode($this->input->post('content'));
        
        file_put_contents($entity->project->viewsTemplatesPath() . $viewName . '.tpl', $content);
    }

    public function edit($entityID, $viewName) 
    {
        $data['entity']     = new Entity($entityID);
        $data['project']    = $data['entity']->project;
        $data['user']       = Projects::security($data['project']->id, "member");
        $data['view']       = $viewName;
        $data['components'] = Component::getAll();

        $this->smartyview->render('view_edit.html', $data);
    }

    public function delete($entityID, $viewName)
    {
        $entity  = new Entity($entityID);
        $project = $entity->project;
        $user    = Projects::security($project->id, "member");
        $file    = $project->viewsTemplatesPath() . $viewName . '.tpl';

        if (file_exists($file)) {
            unlink($file);
        }

        redirect(base_url() . 'projects/dashboard/' . $project->id . '/');
    }

    public function compile($entityID, $viewName)
    {
        $entity = new Entity($entityID);
        $entity->compileView($viewName);
    }
} // class Views

/* End of file views.php */
/* Location: ./application/controllers/views.php */